<template>
  <div class="dialog">
    <el-dialog
      :title="title"
      :visible="dialogFormVisible"
      :modal-append-to-body="false"
      :before-close="closeDialog"
    >
      <el-form
        :model="form"
        :rules="DialogFormRules"
        :ref="dialogFormRef"
        label-position="left"
      >
        <slot
          v-bind="{
            title,
            form,
            formLabelWidth,
            roles
          }"
        >
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              prefix-icon="el-icon-search"
              v-model="form.username"
              clearable
              autocomplete="off"
              :disabled="type == 'edit'"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            :label-width="formLabelWidth"
            prop="password"
            v-if="type === 'create'"
          >
            <el-input
              prefix-icon="el-icon-search"
              clearable
              v-model="form.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input
              prefix-icon="el-icon-search"
              clearable
              v-model="form.email"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="email"
          >
            <el-input
              prefix-icon="el-icon-search"
              clearable
              v-model="form.mobile"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </slot>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addUser, updateUser, setUserRole } from '@/api/user'
import { getRoles } from '@/api/role'

export default {
  name: 'Dialog',
  props: {
    type: {
      type: String,
      default: ''
    },
    dialogFormVisible: Boolean,
    title: {
      type: String,
      default: ''
    },
    form: {
      type: Object,
      default: () => {}
    },
    formLabelWidth: {
      type: String,
      default: '100px'
    }
  },
  methods: {
    closeDialog() {
      this.$emit('closeDialog')
    },
    submitForm() {
      const { type } = this
      if (type === 'allot') {
        const { id, roleId } = this.form
        setUserRole({
          id,
          data: {
            rid: roleId
          }
        }).then(() => {
          this.$emit('getUserList')
          this.closeDialog()
        })
      } else {
        this.$refs.dialogFormRef.validate(async valid => {
          if (valid) {
            const user = this.form
            try {
              if (type === 'create') {
                const { data: res } = await addUser(user)
                this.$emit('getUserList')
                this.closeDialog()
              } else if (type === 'edit') {
                await updateUser({
                  id: user.id,
                  data: {
                    email: user.email,
                    mobile: user.mobile
                  }
                })
                this.closeDialog()
              }
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    async getRoles() {
      const { data: res } = await getRoles()
      this.roles = res
    }
  },
  watch: {
    type: function(newType) {
      if (newType === 'allot') {
        this.getRoles()
      }
    }
    // form: {
    //   handler: function(newVal, oldVal) {
    //     console.log(newVal, oldVal)
    //   },
    //   deep: true
    // }
  },
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      // 判断邮箱是否合法
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      // 不合法
      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^1[0-9]{10}$/
      // 判断手机号的合法性
      if (regMobile.test(value)) {
        // 合法的手机号
        return cb()
      }
      // 不合法的手机号
      cb(new Error('请输入合法的手机号'))
    }
    return {
      dialogFormRef: 'dialogFormRef',
      roles: [],
      // 添加表单的验证规则对象
      DialogFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-dialog {
  position: fixed;
}
</style>
